from ..utils.token import check_activate_token
from ..utils.decimal_to_float import decimal_to_float
from flask import Blueprint, jsonify, request, session
from ..extensions import jys_db, qhjy_db
import time
from decimal import Decimal

personal = Blueprint('personal', __name__)


# 个人基本信息
@personal.route('/', methods=['GET', 'POST'])
def index():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session['id']
        res = jys_db.selectone('select * from bf_user where id=%d' % int(user_id))
        decimal_to_float(res)
        return jsonify({'code': 1, 'data': res, 'msg': ''})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 个人资金信息
@personal.route('/finance/', methods=['GET', 'POST'])
def finance():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session['id']
        # 汇率
        eth_price = jys_db.selectone('select price from tw_eth where id=1')["price"]
        btc_price = jys_db.selectone('select price from tw_btc where id=1')["price"]
        res = jys_db.selectone('select * from bf_user_coin where userid=%d' % int(user_id))
        if res:
            res["all_price"] = int(res["eth"] * eth_price + res["btc"] * btc_price)
            decimal_to_float(res)
            return jsonify({'code': 1, 'data': res, 'msg': ''})
        else:
            return jsonify({'code': 0, 'data': '', 'msg': '用户无资金信息'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 个人充币信息
@personal.route('/tw_myzr/', methods=['GET', 'POST'])
def tw_myzr():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session['id']
        datas = jys_db.selectall('select * from tw_myzr where userid=%d' % int(user_id))
        if datas:
            for data in datas:
                decimal_to_float(data)
            return jsonify({'code': 1, 'datas': datas, 'msg': ''})
        else:
            return jsonify({'code': 0, 'datas': '', 'msg': '无个人提币信息'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 个人提币信息
@personal.route('/tw_myzc/', methods=['GET', 'POST'])
def tw_myzc():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session["id"]
        datas = jys_db.selectall('select * from tw_myzc where userid=%d' % int(user_id))
        if datas:
            for r in datas:
                decimal_to_float(r)
            return jsonify({'code': 1, 'datas': datas, 'msg': ''})
        else:
            return jsonify({'code': 0, 'data': '', 'msg': '用户无提币信息'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 个人场外交易买卖订单
@personal.route('/tw_order_buy/', methods=['GET', 'POST'])
def tw_order_buy():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session["id"]
        # res = jys_db.selectall('select * from tw_order_buy where buy_id=%d or sell_id=%d' % (int(user_id),int(user_id)))

        sql = 'select id,type,deal_coin,status,deal_price,deal_num,order_no,ctime,buy_id,sell_id from tw_order_sell where sell_id=%d or buy_id=%d UNION  select id,type,deal_coin,status,deal_price,deal_num,order_no,ctime,buy_id,sell_id from tw_order_buy where buy_id=%d or sell_id=%d;' % (
        user_id, user_id, user_id, user_id)
        res = jys_db.selectall(sql)
        if res:
            res = sorted(res, key=lambda x: x["ctime"], reverse=True)
            for r in res:
                decimal_to_float(r)
            return jsonify({'code': 1, 'datas': res, 'msg': ''})
        else:
            return jsonify({'code': 0, 'datas': '', 'msg': '场外交易记录为空'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 个人购买期货记录(类型,时间,期数,回报率,结果,购买数量,盈利金额,交割状态)
@personal.route('/qh_betting/', methods=['GET', 'POST'])
def qh_betting():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session["id"]
        bets = qhjy_db.selectall(
            'select qh_betting.tw_qh_coin,qh_betting.type,qh_betting.add_time,qh_nper.nper,qh_nper.result_rate,is_current,qh_nper.result,qh_betting.price,qh_betting.poundage from qh_betting INNER  JOIN qh_nper on qh_betting.nper_id=qh_nper.id where user_id=%d order by add_time DESC ' % int(
                user_id))
        if bets:
            for bet in bets:
                if bet["result"] == bet["type"]:
                    bet['profit'] = round(bet["price"] * Decimal(bet["result_rate"]) - Decimal(bet["poundage"]), 6)
                else:
                    bet["profit"] = -float(bet["price"])
                for k, v in bet.items():
                    if isinstance(v, Decimal):
                        bet[k] = round(float(v), 5)
            return jsonify({'code': 1, 'datas': bets, 'msg': ''})
        else:
            return jsonify({'code': 0, 'data': '', 'msg': '用户期货记录为空'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 汇率
@personal.route('/vote/', methods=['GET', 'POST'])
def vote():
    #price为1个比特币价格,十分钟更新
    btc_price = float(jys_db.selectone('select price from tw_btc where id=1')["price"])
    eth_price = float(jys_db.selectone('select price from tw_eth where id=1')["price"])
    return jsonify({'code': 1, 'data': {"btc_price": btc_price, "eth_price": eth_price}, 'msg': ''})


# 倒计时
@personal.route('/last/', methods=['GET', 'POST'])
# 个人场外挂单信息(
@personal.route('/bf_trade/', methods=['GET', 'POST'])
def bf_trade():
    token = request.cookies.get('token')
    if token and check_activate_token(token) and check_activate_token(token) == session['id']:
        user_id = session["id"]
        res = jys_db.selectall('select * from bf_trade where userid=%d' % int(user_id))
        if res:
            for r in res:
                r['usrename'] = session['username']
                r['mobile'] = session['mobile']
                decimal_to_float(r)
            return jsonify({'code': 1, 'datas': res, 'msg': ''})
        else:
            return jsonify({'code': 0, 'data': '', 'msg': '用户无个人场外交易信息'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


from datetime import datetime


@personal.route('/open/', methods=['GET', 'POST'])
def open():
    m = (datetime.now().minute) % 10
    s = datetime.now().second
    if m == 4 and s in range(50, 60):
        return jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    # 获得配置参数
    config = qhjy_db.selectone('select is_open,btc_error,eth_error from qh_config')
    if not config['is_open']:
        return jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    if config['btc_error'] == 1:
        return jsonify({'code': 0, 'data': '', 'msg': 'BTC正在维护中'})
    if config['eth_error'] == 1:
        return jsonify({'code': 0, 'data': '', 'msg': 'ETH正在维护中'})
    return jsonify({'code': 1, 'data': '', 'msg': '正常工作'})
